<template>
  <el-container>
    <el-header v-if="canEdit">
      <el-input v-model="dicFilterText" placeholder="输入关键字过滤">
        <template #append>
          <el-button type="primary" @click="addDic">
            <el-icon>
              <ElIconFolderAdd />
            </el-icon>
          </el-button>
        </template>
      </el-input>
    </el-header>
    <el-main class="nopadding">
      <el-tree
        ref="dic"
        class="menu tree"
        node-key="id"
        :data="dicList"
        :props="dicProps"
        :highlight-current="true"
        :expand-on-click-node="true"
        :indent="0"
        :filter-node-method="dicFilterNode"
        :default-expanded-keys="expanded"
        icon=""
        @node-click="dicClick"
      >
        <template #default="{ node, data }">
          <el-row style="width: 100%">
            <el-col :span="12" class="custom-tree-node">
              <span class="label"> {{ node.label }}</span>
            </el-col>
            <el-col v-if="canEdit" :span="10" class="do">
              <el-icon @click.stop="dicEdit(data)"><el-icon-edit /></el-icon>
              <el-icon @click.stop="dicDel(node, data)"><el-icon-delete /></el-icon>
            </el-col>
          </el-row>
        </template>
      </el-tree>
    </el-main>
  </el-container>
  <dic-dialog
    v-if="dialog.dic"
    ref="dicDialog"
    :url="url"
    @success="handleDicSuccess"
    @closed="dialog.dic = false"
    :showfield="showfield"
  ></dic-dialog>
</template>

<script>
import dicDialog from "./dic";

export default {
  name: "category",
  emits: ["select"],
  components: {
    dicDialog,
  },
  props: {
    url: {
      type: Object,
      default: () => {
        return {
          list: {
            get: () => {
              return { data: [] };
            },
            reSetParam: () => {
              [];
            },
          },
        };
      },
    },
    params: {
      type: Object,
      default: () => {},
    },
    config: {
      type: Object,
      default: () => {
        return {
          showDicloading: true,
          dicList: [],
          dicFilterText: "",
          dicProps: { label: "" },
          selectId: 0,
        };
      },
    },
    grid: {},
    editable: {
      type: Boolean,
      default: true,
    },
    expandedall: {
      type: Boolean,
      default: true,
    },
    showfield: {
      type: String,
      default: "name",
    },
  },
  data() {
    let defaultConfig = Object.assign(
      {
        showDicloading: true,
        dicList: [],
        dicFilterText: "",
        dicProps: { label: "" },
        selectId: 0,
      },
      this.config
    );
    var AllList = { id: 0, code: "" };
    var fields = this.showfield.split(".");
    if (fields.length == 1) {
      AllList[fields[0]] = "全部";
    } else {
      AllList[fields[0]] = {};
      AllList[fields[0]][fields[1]] = "全部";
    }
    defaultConfig.dicProps["label"] = (data) => {
      var _lable = data;
      fields.forEach((v) => {
        _lable = _lable[v];
      });
      return _lable;
    };

    return {
      dialog: {
        dic: false,
        info: false,
      },
      defaultList: AllList,
      showDicloading: defaultConfig.showDicloading,
      dicList: defaultConfig.dicList,
      dicFilterText: defaultConfig.dicFilterText,
      dicProps: defaultConfig.dicProps,
      selectId: defaultConfig.selectId,
      childrenIds: [],
      canEdit: this.editable,
      expanded: [0],
    };
  },
  watch: {
    dicFilterText(val) {
      this.$refs.dic.filter(val);
    },
  },
  mounted() {
    if (this.dicList.length == 0) this.getDic();
  },
  methods: {
    expandedAllChild(data) {
      data.map((item) => {
        this.expanded.push(item.id);
        if (item["children"]) {
          this.expandedAllChild(item["children"]);
        }
      });
    },
    setParams() {
      let defaultparams = null;
      let urlparams = [];
      if (typeof this.params === "function") defaultparams = this.params();
      else defaultparams = this.params;
      defaultparams = defaultparams instanceof Array ? defaultparams : [defaultparams];
      defaultparams?.forEach((elm) => {
        let urlparam = {};
        for (let k in elm)
          if (this.row && this.row[elm[k]]) {
            urlparam[k] = this.row[elm[k]];
          } else urlparam[k] = elm[k];
        urlparams.push(urlparam);
      });
      return urlparams;
    },
    //加载树数据
    async getDic() {
      let res = {};
      if (this.url.list) res = await this.url.list.reSetParam(this.setParams()).get();
      else res = await this.url.reSetParam(this.setParams()).get();

      this.showDicloading = false;
      if (res.data.length > 1) {
        this.dicList.push(this.defaultList);
        this.dicList[0]["children"] = res.data;
      } else {
        this.dicList = res.data;
      }
      if (this.expandedall) {
        this.expandedAllChild(this.dicList);
      }
      // res.data.forEach((v) => {
      //   this.expanded.push(v.id);
      // });
      //获取第一个节点,设置选中 & 加载明细列表
      if (this.dicList) {
        var firstNode = this.dicList[0];
        if (firstNode) {
          this.$nextTick(() => {
            this.$refs.dic.setCurrentKey(firstNode.id);
          });
          this.selectId = firstNode.id;
        }
      }
    },
    //树过滤
    dicFilterNode(value, data) {
      if (!value) return true;
      var targetText = data.name + data.code;
      return targetText.indexOf(value) !== -1;
    },
    //树增加
    addDic() {
      this.dialog.dic = true;
      this.$nextTick(() => {
        this.$refs.dicDialog.open();
      });
    },
    //编辑树
    dicEdit(data) {
      this.dialog.dic = true;
      this.$nextTick(() => {
        var editNode = this.$refs.dic.getNode(data.id);
        var editNodeParentId = editNode.level == 1 ? undefined : editNode.parent.data.id;
        data.parent_id = editNodeParentId;
        this.$refs.dicDialog.open("edit").setData(data);
      });
    },
    //树点击事件
    dicClick(data) {
      this.childrenIds = [];
      this.$emit("select", data, this.getIds([data]));
    },
    getIds(data) {
      data.forEach((element) => {
        this.childrenIds.push(element.id);
        if (element.children.length > 0)
          Object.assign(this.childrenIds, this.getIds(element.children));
      });
      return this.childrenIds;
    },
    //删除树
    dicDel(node, data) {
      this.$confirm(`确定删除 ${data.name} 项吗？`, "提示", {
        type: "warning",
      })
        .then(async () => {
          this.showDicloading = true;
          //删除节点是否为高亮当前 是的话 设置第一个节点高亮
          var res = await this.url.delete.get({
            id: data.id,
          });
          if (res.code == 200) {
            this.getDic();
            // this.$refs.dic.remove(data.id);
            this.$message.success("操作成功");
            this.showDicloading = false;
          } else {
            this.$alert(res.message, "提示", { type: "error" });
          }
        })
        .catch(() => {
          this.showDicloading = false;
        });
    },

    //本地更新数据
    handleDicSuccess() {
      this.getDic();
    },
  },
};
</script>

<style>
.tree .el-tree-node {
  position: relative;
  padding-left: 0;
}

.tree .el-tree-node__children {
  padding-left: 19px;
}

.tree .el-tree-node :last-child:before {
  height: 12px;
}

.tree .el-tree-node:before {
  content: "";
  left: -3px;
  position: absolute;
  right: auto;
  border-width: 1px;
  border-left: 1px dotted #abaaaa;
  bottom: 0px;
  height: 100%;
  top: 0px;
  width: 1px;
}

.tree .el-tree-node:after {
  content: "";
  left: -3px;
  position: absolute;
  right: auto;
  border-width: 1px;
  border-top: 1px dotted #c0b7b7;
  height: 12px;
  top: 12px;
  width: 12px;
}
</style>
